﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Abp.Migration
{
   public class SqlServerForeignKeyProvider : IForeignKeyProvider
    {
        public string GetForeignKey(string schemaName, string tableName, string columnName, string refSchemaName, string refTableName, string refColumnName)
        {
            string fkName = string.Format("FK_{0}_{1}_{2}_Ref_{3}_{4}_{5}",schemaName,tableName,columnName,refSchemaName,refTableName,refColumnName);
            return string.Format(@"IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE NAME= '{1} ' AND XTYPE= 'F ')
ALTER TABLE {0} DROP CONSTRAINT {1}
ALTER TABLE {0} ADD CONSTRAINT {1} 
    FOREIGN KEY ({2})
    REFERENCES {3}({4})
", GetTableName(schemaName, tableName), fkName, WrapperWith(columnName), GetTableName(refSchemaName, refTableName),WrapperWith(refColumnName));
        }

        private string WrapperWith(string orgin,string start="[",string end="]")
        {
            if (string.IsNullOrWhiteSpace(orgin))
                return string.Empty;
            if (!orgin.StartsWith(start))
                orgin = start + orgin;
            if (!orgin.EndsWith(end))
                orgin = orgin + end;
            return orgin;
        }

        private string GetTableName(string schemaName,string tableName)
        {
            string result = WrapperWith(schemaName);
            if (string.IsNullOrWhiteSpace(result))
                result = WrapperWith(tableName);
            else
                result+="."+ WrapperWith(tableName);
            return result;

        }
    }
}
